﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.model;
using l1cs.server.templates;
using l1cs.server.datatables;
using l1cs.server.model.Instance;

namespace l1cs.server.serverpackets
{
    public class S_ShopSellList : ServerBasePacket
    {
        /**
         * 店の品物リストを表示する。キャラクターがBUYボタンを押した時に送る。
         */
        public S_ShopSellList( int objId )
        {
            writeC( Opcodes.S_OPCODE_SHOWSHOPBUYLIST );
            writeD( objId );

            L1Object npcObj = L1World.getInstance().findObject( objId );
            if ( !( npcObj is L1NpcInstance ) )
            {
                writeH( 0 );
                return;
            }
            int npcId = ( (L1NpcInstance)npcObj ).getNpcTemplate().get_npcId();

            L1TaxCalculator calc = new L1TaxCalculator( npcId );
            L1Shop shop = ShopTable.getInstance().get( npcId );
            List<L1ShopItem> shopItems = shop.getSellingItems();

            writeH( shopItems.Count );

            // L1ItemInstanceのgetStatusBytesを利用するため
            L1ItemInstance dummy = new L1ItemInstance();

            for ( int i = 0; i < shopItems.Count; i++ )
            {
                L1ShopItem shopItem = shopItems[i];
                L1Item item = shopItem.getItem();
                int price = calc.layTax( (int)( shopItem.getPrice() * Config.RATE_SHOP_SELLING_PRICE ) );
                writeD( i );
                writeH( shopItem.getItem().getGfxId() );
                writeD( price );
                if ( shopItem.getPackCount() > 1 )
                {
                    writeS( item.getName() + " (" + shopItem.getPackCount() + ")" );
                }
                else
                {
                    writeS( item.getName() );
                }
                L1Item template = ItemTable.getInstance().getTemplate( item.getItemId() );
                if ( template == null )
                {
                    writeC( 0 );
                }
                else
                {
                    dummy.setItem( template );
                    byte[] status = dummy.getStatusBytes();
                    writeC( status.Length );
                    foreach ( byte b in status )
                    {
                        writeC( b );
                    }
                }
            }
            writeH( 0x07 ); // 0x00:kaimo 0x01:pearl 0x07:adena
        }

        override
        public byte[] getContent()
        {
            return _bao.ToArray();
        }

        override public String getType()
        {
            return "[S] S_ShopSellList";
        }
    }
}
